﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace IveelySE.Dream.Common.Transmission
{
    /// <summary>
    /// 服务端信息处理
    /// </summary>
    public class ServerProcesspor
    {
        /// <summary>
        /// TCP客户端
        /// </summary>
        private TcpClient tcpClient;

        /// <summary>
        /// TCP监听器
        /// </summary>
        private TcpListener tcpListener = null;

        public ServerProcesspor()
        {

        }

        /// <summary>
        /// 返回客户端信息集合
        /// </summary>
        /// <returns></returns>
        public List<ClientInfo> GetClientInfo()
        {
            return ServerHelper.GetClientInfos();
        }

        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="port">启动端口</param>
        public void Start(int port)
        {
            foreach (TcpClient client in ServerHelper.GetClients())
            {
                if (client != null)
                {
                    if (client.GetStream() != null)
                    {
                        client.GetStream().Close();
                    }

                    client.Close();
                }
            }
            ServerHelper.CleanClientInfos();
            ServerHelper.StartListening(ref tcpListener, port);
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop()
        {
            foreach (TcpClient client in ServerHelper.GetClients())
            {
                if (client != null)
                {
                    if (client.GetStream() != null)
                    {
                        client.GetStream().Close();
                    }

                    client.Close();
                }
            }
            ServerHelper.CleanClientInfos();
            ServerHelper.StopListening(ref tcpListener);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="commandType"></param>
        /// <param name="command"></param>
        /// <param name="parameters"></param>
        public void SendToClient(string commandType, string command, string[] parameters)
        {
            foreach (TcpClient client in ServerHelper.GetClients())
            {
                ClientHelper.SendMessage(client, "1");
            }
        }

        public void Close()
        {
            ClientHelper.Close(tcpClient);
        }
    }
}
